Check if row exists, if not add it [MySQL]

Posted by Steven on Stack Overflow See other posts from Stack Overflow or by Steven
Published on 2011-02-08T23:23:53Z Indexed on 2011/02/08 23:25 UTC
Read the original article Hit count: 232

Filed under:
|

I need to add a row to a MySQL database table but only if the row doesn't already exist. My database server just went down so I can't test this, but will this work as expected?

INSERT INTO `blocks` (`block_file`,`settings_group`)
VALUES ('announcements','announcement_settings')
WHERE NOT EXISTS (SELECT `block_file`,`settings_group`
                  FROM `blocks`
                  WHERE `block_file`='announcements' AND `settings_group`='announcement_settings')

It seems like sound logic. Is this a valid query or is there a better way of doing this?

© Stack Overflow or respective owner

Related posts about mysql

Related posts about insert